const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const expressJwt = require('express-jwt');
const vertoken = require('./token/token')
const host = 'http://localhost:8888';
// 图片上传
const fs = require('fs');
const multer  = require('multer');
const upload = multer({ dest: __dirname + '/uploads' });
// 
const app = express();
// 处理跨域
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))


// 验证token
app.use(function(req, res, next) {
    var token = req.headers['authorization'];
    if(token === undefined){
        return next();
    }else{
        vertoken.getToken(token).then((data)=> {
            req.data = data;
            return next();
        }).catch((error)=>{
            return next();
        })
    }
});
//验证token是否过期并规定那些路由不需要验证
app.use(expressJwt({
    secret:'ybkkeys',
    algorithms:['HS256']
}).unless({
    path:[
    { url:'/login/user',methods:['POST']},
    { url:'/login/admin',methods:['POST']},
    { url:'/register',method:['POST']},
    { url:'/upload',method:['POST']},
    { url:/\/uploads\/[a-zA-Z0-9_-]+/,methods:['GET']}
    
]  //不需要验证的接口名称
}))

//token失效返回信息
app.use((err, req, res, next) => {
    if (err.status === 401) {
        return res.status(err.status).json({
            status: err.status,
            msg: '没有登录',
            error: err.name + ':' + err.message
        })
    }
})



// 登录接口
const login = require('./route/login')
app.use('/login',login);
// 注册接口
const register = require('./route/register')
app.use('/register',register);
// 菜单接口
const menu = require('./route/menu');
app.use('/menu',menu);
// 用户相关接口-------
const user = require('./route/user')
app.use('/user',user);
// 场地相关接口
const court = require('./route/court')
app.use('/court',court);
// 球馆相关接口 
const stadium = require('./route/stadium');
app.use('/stadium',stadium);
// 订单相关接口
const order = require('./route/order');
app.use('/order',order);
// 评论相关接口
const comment = require('./route/comment');
app.use('/comment',comment);
// 公告相关接口
const notice = require('./route/notice');
app.use('/notice',notice);
// 首页相关接口
const home = require('./route/home');
app.use('/home',home);
// ------------------
// 单图上传
app.post('/upload',upload.single('file'),async (req,res)=>{
    const file = req.file; 
    file.url = `${host}/uploads/${file.filename}`;
    res.send(file);
 
})
app.use('/uploads', express.static(__dirname + '/uploads'));

app.listen(8888,()=>{
    console.log('服务启动');
})